/*
* 签名
* */

import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'dart:io';

import 'package:orientation/orientation.dart';
class Sign extends StatefulWidget {
  const Sign();

  @override
  _SignState createState() => _SignState();
}

class _SignState extends State<Sign> {
  GlobalKey key = GlobalKey();
  List<Offset> _points = [];
  Uint8List _postBytes;
  _saveSignPic() async {
    RenderRepaintBoundary boundary =
    key.currentContext.findRenderObject() as RenderRepaintBoundary;
    var image = await boundary.toImage(pixelRatio: 3.0);
    ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
    _postBytes = byteData?.buffer.asUint8List();
    Get.back(result: _postBytes);
    //保存到相册
    // var result = await ImageGallerySaver.saveImage(_postBytes!);
    // String path = result['filePath'].replaceAll("file://", '');
    // if (result != null && result != "") {
    //   //上传到服务器
    //   SelectFileUtil.uploadFile(
    //       path, "sign_${DateTime.now().microsecondsSinceEpoch}.png",
    //       successCallback: (url) {
    //         //拿到服务器返回图片地址,退出页面
    //         if (url != null && url.isNotEmpty) {
    //           if (!mounted) return;
    //           Navigator.of(context).pop(url);
    //         }
    //       });
    // }
  }


  @override
  void initState() {
    // TODO: implement initState
    super.initState();

  }

  @override
  void deactivate() {
    // TODO: implement deactivate

    super.deactivate();
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
    print('这里');
    if(Platform.isIOS){
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.landscapeRight,
      ]);
    }
    OrientationPlugin.forceOrientation(DeviceOrientation.landscapeRight);
  }


  @override
  Widget build(BuildContext context) {
    return WillPopScope(child: Scaffold(
        appBar: AppBar(
          title: Text('签名'),
          actions: [
            new Container(
              child: FlatButton(
                child: new Text(
                  "确定",
                  style: TextStyle(color: Colors.white),
                ),
                onPressed: () {
                  _saveSignPic();
                  SystemChrome.setPreferredOrientations([
                    DeviceOrientation.portraitUp,
                  ]);
                  OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp);
                },
              ),
            ),
          ],
        ),
        body: RepaintBoundary(
          key: key,
          child: Container(
            child: GestureDetector(
              onPanUpdate: (DragUpdateDetails details) {
                print("$details======onPanUpdate");
                this.setState(() {
                  _points.add(details.localPosition);
                });
              },
              onPanEnd: (DragEndDetails details) {
                print(details);
                this.setState(() {
                  _points.add(null);
                });
              },
              child: CustomPaint(
                foregroundPainter:SketchPainter(this._points),
                child: Container(
                  color: Colors.white,
                ),
              ),
            ),
          ),
        )
    ), onWillPop: () {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
      ]);
      OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp);
      return Future.value(true);
    });
  }
}
class SketchPainter extends CustomPainter {
  final List<Offset> points;

  SketchPainter(this.points);

  static Paint _pen = Paint();

  @override
  void paint(Canvas canvas, Size size) {
    // TODO: implement paint
    _pen.strokeWidth = 4.0;
    for (int i = 0; i < points.length - 1; i++) {
      if (points[i] != null && points[i + 1] != null) {
        canvas.drawLine(points[i], points[i + 1], _pen);
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }

}
